package com.cyb.beta.service;

import com.cyb.beta.core.Constant;
import com.cyb.beta.model.RoleUser;
import com.cyb.beta.model.User;
import com.cyb.beta.utils.DateUtils;
import com.jfinal.plugin.activerecord.Page;
import org.apache.shiro.SecurityUtils;

import java.util.List;

/**
 * Created by Administrator on 2015/6/15.
 */
public class UserService {
    public Page<User> getUserPage(int pageNumber, int pageSize, User user) {
        return User.dao.searchPaginate(pageNumber, pageSize, user);
    }

    public boolean modifyUser(User user, String[] roleIds) {
        boolean flag = true;
        Long id = user.getLong(User.ID);

        if (null == id) {
            User checkUser = User.dao.findFirst("select * from s_user where username=?", user.getStr(User.USERNAME));
            if (null == checkUser) {
                User loginUser = (User) SecurityUtils.getSubject().getSession().getAttribute(Constant.SHIRO_USER);
                // 创建时间，删除状态，启用状态
                user.set(User.CREATE_TIME, DateUtils.getCurrentTime())
                        .set(User.CREATE_USER_ID, loginUser.getLong(User.ID))
                        .set(User.PASSWORD, Constant.DEFAULT_PASSWORD)
                        .save();
            } else {
//                message = "用户名已经存在";
                flag = false;
            }
        } else {
            RoleUser.dao.deleteByUserId(id); // 删除用户角色信息
            // 更新时间
            user.set(User.UPDATE_TIME, DateUtils.getCurrentTime())
                    .update();
        }
        // 用户绑定角色
        if (null != roleIds && flag) {
            RoleUser roleUser = null;
            for (String roleId : roleIds) {
                roleUser = new RoleUser();
                roleUser.set(RoleUser.ROLE_ID, roleId)
                        .set(RoleUser.USER_ID, id)
                        .save();
            }
        }

        return flag;
    }

    public void deleteUsers(String[] ids) {
        //TODO 删除绑定角色

        User.dao.deleteByIds(ids);
    }

    public String getUserRole(Long userId) {
        StringBuilder stringBuilder = new StringBuilder();
        List<RoleUser> roleUsers = RoleUser.dao.searchRoleUserByUserId(userId);
        stringBuilder.append("-");
        for (RoleUser roleUser : roleUsers) {
            stringBuilder.append(roleUser.getInt(RoleUser.ROLE_ID));
            stringBuilder.append("-");
        }
        return stringBuilder.toString();
    }
}
